'use strict';
const dayjs = require("dayjs");
const getNumberValue = function (value) {
    let numberValue = Number(value);
    return isNaN(numberValue) ? 0 : numberValue;
}
module.exports = app => {
  const { STRING, INTEGER, TEXT, DATE, DECIMAL } = app.Sequelize;
  const Cycle = app.model.define(
      'Cycle',
      {
          id: {type: INTEGER, primaryKey: true, autoIncrement: true},
          ship_id: INTEGER,
          count: {
              type: DECIMAL(10,1),
              get() {
                  return getNumberValue(this.getDataValue('count'))
              }
          },
          price: {
              type: DECIMAL(10, 2),
              get() {
                  return getNumberValue(this.getDataValue('price'))
              }
          },
          child_price: {
              type: DECIMAL(10, 2),
              get() {
                  return getNumberValue(this.getDataValue('child_price'))
              }
          },
          start_time: {
                  type: DATE,
                  get() {
                      return dayjs(this.getDataValue('start_time')).format('YYYY-MM-DD HH:mm:ss');
                  }
              },
          end_time: {
              type: DATE,
              get() {
                  return dayjs(this.getDataValue('end_time')).format('YYYY-MM-DD HH:mm:ss');
              }
          },
          duration: {
              type: DECIMAL(10,1),
              get() {
                  return getNumberValue(this.getDataValue('duration'))
              }
          },
          status: INTEGER,
          create_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
                },
              set() {
                    // 使用澳大利亚时区

              }
            },
      },
      {
          tableName: 'cycle',
          timestamps: true, // 启用时间戳(createdAt, updatedAt)
          updatedAt: 'updated_time', // 不想要 updatedAt
          createdAt: 'create_time', // 想要  createdAt 但是希望名称叫做 created_at
      }
  );
    Cycle.associate = function() {
        // 关联ship表
        app.model.Cycle.belongsTo(app.model.Ship, { foreignKey: 'ship_id', targetKey: 'id', as: 'ship' });
        // 关联了订单
        app.model.Cycle.hasMany(app.model.Order, { foreignKey: 'cycle_id', targetKey: 'id', as: 'orderList' });
        // 关联订单详情
        app.model.Cycle.hasMany(app.model.OrderUser, { foreignKey: 'cycle_id', targetKey: 'id', as: 'orderUserList' });
    }
    return Cycle
};
